package org.example.service.impl;

import org.example.Mapper.*;
import org.example.domain.Activity;
import org.example.domain.Admin;
import org.example.domain.User;
import org.example.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.Objects;

@Service
public class AdminServiceImpl implements AdminService {

    @Autowired
    private AdminMapper adminMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private ActivityRecordMapper activityRecordMapper;

    @Autowired
    private ActivityMapper activityMapper;

    @Autowired
    private ApplyRecordMapper applyRecordMapper;

    @Autowired
    private EmailRecordMapper emailRecordMapper;

    @Override
    public Admin login(Admin admin) {
        Admin sqlAdmin= adminMapper.login(admin.getAccount());
        if(sqlAdmin==null){
            return null;
        } else if(sqlAdmin.getPassword().equals(admin.getPassword())){
            return sqlAdmin;
        } else {
            return null;
        }
    }

    @Override
    public boolean registerByAdmin(String account,String password,String name,String className){
        User user=userMapper.login(account);
        if(user!=null){//学生已存在
            return false;
        } else {//学生不存在，注册成功
            userMapper.registerByAdmin(account,password,name,className,new Date());
            return true;
        }
   }

   @Override
   public Integer forceJoin(Integer userId, Integer activityId) {//管理员帮助学生强制报名
       Integer[] userIds=activityRecordMapper.getUserIdsByActivityId(activityId);//先获取所有报名参加了
       Activity activity=activityMapper.getAllById(activityId);
       if (activity.getIsSignIn()==1){//活动已经签到
           return 2;
       }
       // 这项活动的人员id，要避免重复报名
       boolean isIn=false;
       for (Integer userId2 : userIds) {
           if (Objects.equals(userId2, userId)) {
               isIn = true;
               break;
           }
       }
       if(isIn){//该学生已报名参加了这项活动，禁止其再次报名
           return 0;
       } else {//该同学未参加这项活动，查看是否还有报名余额
           activityRecordMapper.addActivityRecord(userId,activityId);//报名成功
           return 1;
       }
   }

    @Override
    public void changeAdminInfo(Admin admin) {
        adminMapper.changeAdminInfo(admin);
    }

    @Override
    public boolean checkAdminOnePassword(String password) {
        Admin admin= adminMapper.checkAdminOnePassword();
        //判断密码是否一致
        return admin.getPassword().equals(password);
    }

    @Override
    public Integer getNumberByUserWhereRegisterStatusEqualZero() {
        return userMapper.getNumberByUserWhereRegisterStatusEqualZero();
    }

    @Override
    public Integer getNumberByEmailRecordWhereAdminIdEqualZero() {
        return emailRecordMapper.getNumberByEmailRecordWhereAdminIdEqualZero();
    }

}
